package com.itheima.activiti.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.itheima.activiti.auth.JwtTokenUtils;
import com.itheima.activiti.dto.system.LoginDTO;
import com.itheima.activiti.dto.system.OrgUserTreeDTO;
import com.itheima.activiti.dto.system.UserDTO;
import com.itheima.activiti.service.system.UserService;
import com.itheima.authority.api.v1.LoginApi;
import com.itheima.authority.api.v1.OrgApi;
import com.itheima.authority.api.v1.UserApi;
import com.itheima.authority.api.v1.dto.LoginExternalDTO;
import com.itheima.authority.api.v1.dto.OrgDTO;
import com.itheima.authority.common.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Value("${itcast.application.id}") //当前应用的id
    private String applicationId;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private LoginApi loginApi;
    @Autowired
    private UserApi userApi;
    @Autowired
    private OrgApi orgApi;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @SneakyThrows
    @Override
    public LoginDTO login(String username, String password) {
        //1、远程验证用户名密码
        LoginDTO loginDTO = new LoginDTO();
        R<LoginExternalDTO> loginResult = loginApi.externalLogin(username, password, applicationId);
        if (loginResult.getIsSuccess()) {
            //2、获得权限系统的用户对象
            com.itheima.authority.api.v1.dto.UserDTO user = loginResult.getData().getUser();

            //3、创建用户对象
            com.itheima.activiti.dto.system.UserDTO userDTO = new com.itheima.activiti.dto.system.UserDTO();
            BeanUtil.copyProperties(user, userDTO);
            userDTO.setApplicationId(applicationId);

            //4、把用户对象序列化成map
            Map<String, String> userMap = new HashMap<>();
            BeanUtil.copyProperties(userDTO, userMap,
                    CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

            //5、生成token
            Map map = new HashMap();
            map.put("user", userMap);
            map.put("password", password);
            String token = jwtTokenUtils.createToken(map);

            //6、返回loginDTO给前台
            if (StringUtils.isNoneBlank(token)) {
                loginDTO.setUserDTO(userDTO);
                loginDTO.setToken(token);
                return loginDTO;
            }
        }
        return null;
    }

    /**
     * 获得所有用户，用于：
     * 设计流程图中选择用户
     *
     * @return
     */
    @Override
    public List<UserDTO> list() {
        R<List<com.itheima.authority.api.v1.dto.UserDTO>> userResult = userApi.list(null, null, null, null, null);
        List<UserDTO> userDTOList = new ArrayList<>();
        if (userResult.getIsSuccess()) {
            for (com.itheima.authority.api.v1.dto.UserDTO datum : userResult.getData()) {
                UserDTO userDTO = new UserDTO();
                BeanUtil.copyProperties(datum, userDTO);
                userDTOList.add(userDTO);
            }
        }
        return userDTOList;
    }

    /**
     * 获得操作人的上级
     *
     * @param assignee
     * @return
     */
    @Override
    public String getSuperior(String assignee) {
        R<com.itheima.authority.api.v1.dto.UserDTO> userR = userApi.get(Long.valueOf(assignee));
        if (userR.getIsSuccess() && userR.hasObjectData()) {
            Long id = userR.getData().getSuperior();
            userR = userApi.get(id);
            if (userR.getIsSuccess() && userR.hasObjectData()) {
                return userR.getData().getId().toString();
            }
        }
        return null;
    }

    /**
     * 获取用户的上级领导
     *
     * @param assignee
     * @return
     */
    @Override
    public String getManager(String assignee) {
        R<com.itheima.authority.api.v1.dto.UserDTO> userR = userApi.get(Long.valueOf(assignee));
        if (userR.getIsSuccess() && userR.hasObjectData()) {
            Long id = userR.getData().getOrgId();
            R<OrgDTO> orgR = orgApi.get(id);
            if (orgR.getIsSuccess() && orgR.hasObjectData()) {
                Long managerId = orgR.getData().getManagerId();
                userR = userApi.get(managerId);
                if (userR.getIsSuccess() && userR.hasObjectData()) {
                    return userR.getData().getId().toString();
                }
            }
        }
        return null;
    }

    /**
     * 根据用户Id获得用户所有的角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getUserRoles(String userId) {
        R<com.itheima.authority.api.v1.dto.UserDTO> userR = userApi.get(Long.valueOf(userId));
        if (userR.getIsSuccess() && userR.hasObjectData()) {
            return userR.getData().getRoles().stream().map(item -> String.valueOf(item)).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 获取组织机构树
     *
     * @return
     */
    @Override
    public List<OrgUserTreeDTO> tree() {
        R<List<com.itheima.authority.api.v1.dto.OrgUserTreeDTO>> orgUserTreeResult = orgApi.orgUserTree();
        List<OrgUserTreeDTO> orgUserTreeDTOList = new ArrayList<>();
        if (orgUserTreeResult.getIsSuccess()) {
            orgUserTreeCopy(orgUserTreeResult.getData(), orgUserTreeDTOList);
        }
        return orgUserTreeDTOList;
    }

    private void orgUserTreeCopy(List<com.itheima.authority.api.v1.dto.OrgUserTreeDTO> orgUserTreeList, List<OrgUserTreeDTO> orgUserTreeDTOList) {
        for (com.itheima.authority.api.v1.dto.OrgUserTreeDTO datum : orgUserTreeList) {
            OrgUserTreeDTO orgUserTreeDTO = new OrgUserTreeDTO();
            BeanUtil.copyProperties(datum, orgUserTreeDTO);
            if (!CollectionUtils.isEmpty(datum.getChildren())) {
                List<OrgUserTreeDTO> orgUserTreeDTOChildrenList = new ArrayList<>();
                orgUserTreeCopy(datum.getChildren(), orgUserTreeDTOChildrenList);
                orgUserTreeDTO.setChildren(orgUserTreeDTOChildrenList);
            }
            orgUserTreeDTOList.add(orgUserTreeDTO);
        }
    }


    /**
     * 根据Id查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public com.itheima.activiti.dto.system.UserDTO getById(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        try {
            R<com.itheima.authority.api.v1.dto.UserDTO> userResult = userApi.get(Long.valueOf(userId));
            if (userResult.getIsSuccess()) {
                UserDTO userDTO = new UserDTO();
                BeanUtil.copyProperties(userResult.getData(), userDTO);
                return userDTO;
            }
        } catch (Exception e) {
            log.warn("查询用户失败:{}", userId, e);
        }
        return null;
    }
}
